import VueRouter from 'vue-router';
import Vue from 'vue';
Vue.use(VueRouter);

// 导入对应的页面组件
import Home from '@/views/Home.vue';
import Topic from '@/views/Topic.vue';
import Category from '@/views/Category.vue';
import Cart from '@/views/Cart.vue';
import User from '@/views/User.vue';
// 搜索页路由
import SearchPop from '@/views/SearchPop.vue';
import Sousuolist from '@/views/SouSuoList.vue';
// 详情页
import ProductDetail from '@/views/ProductDetail.vue';
// 错误消息
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err);
};
// 第一步：创建路由配置
const routes = [
    {
        // path: '/',
        // component: Home,
        // 路由重定向
        //    设置 默认显示首页
        path: '',
        redirect: '/home',
    },
    // 一级路由首页与二级路由搜索页
    {
        path: '/home',
        component: Home,
        name: 'home',
        children: [
            {
                path: 'searchpop',
                component: SearchPop,
                meta: {
                    showtarbar: false,
                },
            },
        ],
        // 设置是否显示
        meta: {
            showtarbar: true,
        },
    },
    // 搜索框信息展示路由
    {
        path: '/sousuo',
        component: Sousuolist,
        meta: {
            showtarbar: false,
        },
    },
    {
        path: '/topic',
        component: Topic,
        name: 'topic',
        meta: {
            showtarbar: true,
        },
    },
    {
        path: '/category',
        component: Category,
        name: 'category',
        meta: {
            showtarbar: true,
        },
    },
    {
        path: '/cart',
        component: Cart,
        name: 'cart',
        meta: {
            showtarbar: true,
        },
    },
    {
        path: '/user',
        component: User,
        name: 'user',
        meta: {
            showtarbar: true,
        },
    },
    {
        path: '/pro',
        component: ProductDetail,
        meta: {
            showtarbar: false,
        },
    },
];

// 第二步：创建路由实例对象
const router = new VueRouter({
    mode: 'history',
    routes,
});

// 路由前置守卫
router.beforeEach((to, from, next) => {
    // console.log(to);
    // 有token就表示已经登录
    // 想要进入购物车页面，必须有登录标识token
    let user = localStorage.getItem('userInfo'); //string或null

    // let token = localStorage.getItem('token');
    // console.log(token);
    if (to.path == '/cart') {
        // 此时必须要有token
        if (user) {
            next(); // next()去到to所对应的路由界面
        } else {
            Vue.prototype.$toast('请先登录');
            // 定时器
            setTimeout(() => {
                next('/user'); // 强制去到"/user"所对应的路由界面
            }, 1000);
        }
    } else {
        // 如果不是去往购物车的路由，则直接通过守卫，去到to所对应的路由界面
        next();
    }
});
export default router;
